package com.wyu.test.web;

import com.wyu.test.entity.CUserEntity;
import com.wyu.test.repository.CAddressEntityRepository;
import com.wyu.test.repository.CUserEntityRepository;
import com.wyu.test.util.JsonCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserAddressWebController {

    @Autowired
    CAddressEntityRepository cAddressEntityRepository;

    @Autowired
    CUserEntityRepository cUserEntityRepository;


    @GetMapping(value = "/userAddress1")
    public String userAddress(HttpServletRequest request,
                              @RequestParam(value = "username",required = true) String username){

        CUserEntity cUserEntity = cUserEntityRepository.findFirstByUsername(username);
        if(cUserEntity == null){
            return new JsonCode<>().ResponseFail(99,"log_out");
        }

        List<Map<String, Object>> address = cAddressEntityRepository.NativeFindByUserId(cUserEntity.getId());
        return new JsonCode<>().ResponseSuccess(address);
    }

    @GetMapping(value = "/userAddress2")
    public String userAddress(HttpServletRequest request,
                              @RequestParam(value="page", required=true) int page,
                              @RequestParam(value = "id",required = false) int id,
                              @RequestParam(value = "username",required = false) String username,
                              @RequestParam(value = "phone",required = false) String phone){

        Pageable firstPageWithTwoElements = PageRequest.of(page, 10);
        Page<Map<String, Object>> address = cAddressEntityRepository.NativeFindAllByUsernameOrPhone(id,username,phone,firstPageWithTwoElements);

        return new JsonCode<>().ResponseSuccess(address);
    }

}
